<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <!-- 基本信息搜索 -->
      <el-form-item label="房间编号" prop="roomNum">
        <el-input
          v-model="queryParams.roomNum"
          placeholder="请输入房间编号"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间名称" prop="roomName">
        <el-input
          v-model="queryParams.roomName"
          placeholder="请输入房间名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 位置信息搜索 -->
      <el-form-item label="所属校区" prop="cellId">
        <el-select
          v-model="queryParams.cellId"
          placeholder="请选择校区"
          clearable
          style="width: 200px"
          @change="handleQueryCellChange">
          <el-option
            v-for="item in cellOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属楼栋" prop="unitId">
        <el-select
          v-model="queryParams.unitId"
          placeholder="请选择楼栋"
          clearable
          style="width: 200px"
          :disabled="!queryParams.cellId"
          @change="handleQueryUnitChange">
          <el-option
            v-for="item in unitOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属楼层" prop="floorId">
        <el-select
          v-model="queryParams.floorId"
          placeholder="请选择楼层"
          clearable
          style="width: 200px"
          :disabled="!queryParams.unitId">
          <el-option
            v-for="item in floorOptions"
            :key="item.id"
            :label="item.floorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 状态信息搜索 -->
      <el-form-item label="房间状态" prop="roomStatus">
        <el-select
          v-model="queryParams.roomStatus"
          placeholder="请选择房间状态"
          clearable
          style="width: 200px">
          <el-option
            v-for="dict in dict.type.home_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 注释掉不常用的搜索条件 -->
      <!-- <el-form-item label="房型类型" prop="roomTypeId">
        <el-select v-model="queryParams.roomTypeId" placeholder="请选择房型类型" clearable>
          <el-option
            v-for="dict in dict.type.home_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="容纳人数" prop="rentablePersonQuantity">
        <el-input
          v-model="queryParams.rentablePersonQuantity"
          placeholder="请输入容纳人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="逻辑删除" prop="deleteFlg">
        <el-input
          v-model="queryParams.deleteFlg"
          placeholder="请输入逻辑删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼层号" prop="floorId">
        <el-input
          v-model="queryParams.floorId"
          placeholder="请输入楼层号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lock:home:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lock:home:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lock:home:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lock:home:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属校区" align="center" prop="cellName" />
      <el-table-column label="所属楼栋" align="center" prop="unitName" />
      <el-table-column label="所属楼层" align="center" prop="floorName" />
      <el-table-column label="房间编号" align="center" prop="roomNum" />
      <el-table-column label="房间名称" align="center" prop="roomName" />
      <el-table-column label="房间状态" align="center" prop="roomStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.home_status" :value="scope.row.roomStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="电池电量" align="center" prop="batteryLevel" />
      <el-table-column label="最后通讯时间" align="center" prop="lastCommunication">
        <template slot-scope="scope">
          <span>{{ scope.row.lastCommunication ? (scope.row.lastCommunication | parseTime('yyyy-MM-dd HH:mm:ss')) : '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="门锁通讯密钥" align="center" prop="secKey" /> -->
      <el-table-column label="管理员密码" align="center" prop="pwd" />
      <!-- <el-table-column label="管理员密码Id" align="center" prop="pwdId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lock:home:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lock:home:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房屋管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基本信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="房间编号" prop="roomNum">
              <el-input v-model="form.roomNum" placeholder="请输入房间编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间名称" prop="roomName">
              <el-input v-model="form.roomName" placeholder="请输入房间名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 房间属性 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="房型类型" prop="roomTypeId">
              <el-select v-model="form.roomTypeId" placeholder="请选择房型类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.home_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="容纳人数" prop="rentablePersonQuantity">
              <el-input v-model="form.rentablePersonQuantity" placeholder="请输入容纳人数" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 位置信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="校区" prop="cellId">
              <el-select v-model="form.cellId" placeholder="请选择校区" style="width: 100%" @change="handleCellChange" clearable>
                <el-option v-for="item in cellOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼栋" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择楼栋" style="width: 100%" :disabled="!form.cellId" clearable @change="handleUnitChange">
                <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 状态信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId">
              <el-select v-model="form.floorId" placeholder="请选择楼层" style="width: 100%" :disabled="!form.unitId" clearable>
                <el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间状态" prop="roomStatus">
              <el-select v-model="form.roomStatus" placeholder="请选择房间状态" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.home_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 图片上传，单独占一行 -->
       <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="房间照片" prop="photo">
              <image-upload v-model="form.photo"/>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHome, getHome, delHome, addHome, updateHome } from "@/api/lock/home";
import { listCell2 } from "@/api/lock/cell";
import { listUnit2 } from "@/api/lock/unit";
import { listFloor2 } from "@/api/lock/floor";

export default {
  name: "Home",
  dicts: ['home_type', 'home_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房屋管理表格数据
      homeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNum: null,
        roomName: null,
        roomStatus: null,
        cellId: null,
        unitId: null,
        // 注释掉不常用的查询参数
        // roomTypeId: null,
        // rentablePersonQuantity: null,
        // deleteFlg: null,
        // photo: null,
        // floorId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roomNum: [
          { required: true, message: "房间编号不能为空", trigger: "blur" }
        ],
        roomName: [
          { required: true, message: "房间名称不能为空", trigger: "blur" }
        ],
        roomTypeId: [
          { required: true, message: "房型类型不能为空", trigger: "change" }
        ],
        rentablePersonQuantity: [
          { required: true, message: "容纳人数不能为空", trigger: "blur" }
        ],
        roomStatus: [
          { required: true, message: "房间状态不能为空", trigger: "change" }
        ],
        cellId: [
          { required: true, message: "所属校区不能为空", trigger: "change" }
        ],
        unitId: [
          { required: true, message: "所属楼栋不能为空", trigger: "change" }
        ],
        floorId: [
          { required: true, message: "所属楼层不能为空", trigger: "change" }
        ]
      },
      cellOptions: [],
      unitOptions: [],
      floorOptions: []
    };
  },
  created() {
    this.getList();
    this.getCellList(); // 获取校区列表
  },
  methods: {
    /** 获取校区列表 */
    getCellList() {
      listCell2().then(response => {
        this.cellOptions = response.rows;
      });
    },
    /** 获取楼栋列表 */
    getUnitList(cellId) {
      this.unitOptions = [];
      this.queryParams.unitId = undefined;
      this.form.unitId = undefined;
      this.floorOptions = [];
      this.queryParams.floorId = undefined;
      this.form.floorId = undefined;

      if (!cellId) return;

      listUnit2({ cellId: cellId }).then(response => {
        this.unitOptions = response.rows;
      });
    },
    /** 获取楼层列表 */
    getFloorList(unitId) {
      this.floorOptions = [];
      this.queryParams.floorId = undefined;
      this.form.floorId = undefined;

      if (!unitId) return;

      listFloor2({ unitId: unitId }).then(response => {
        this.floorOptions = response.rows;
      });
    },
    /** 搜索条件校区选择改变时触发 */
    handleQueryCellChange(value) {
      if (value) {
        listUnit2({ cellId: value }).then(response => {
          this.unitOptions = response.rows;
        });
      } else {
        this.unitOptions = [];
        this.floorOptions = [];
        this.queryParams.unitId = undefined;
        this.queryParams.floorId = undefined;
      }
    },
    /** 搜索条件楼栋选择改变时触发 */
    handleQueryUnitChange(value) {
      if (value) {
        listFloor2({ unitId: value }).then(response => {
          this.floorOptions = response.rows;
        });
      } else {
        this.floorOptions = [];
        this.queryParams.floorId = undefined;
      }
    },
    /** 表单校区选择改变时触发 */
    handleCellChange(value) {
      this.getUnitList(value);
    },
    /** 表单楼栋选择改变时触发 */
    handleUnitChange(value) {
      this.getFloorList(value);
    },
    /** 查询房屋管理列表 */
    getList() {
      this.loading = true;
      listHome(this.queryParams).then(response => {
        this.homeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomNum: null,
        roomName: null,
        roomTypeId: null,
        rentablePersonQuantity: null,
        deleteFlg: null,
        roomStatus: null,
        photo: null,
        cellId: null,
        unitId: null,
        floorId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清空联动数据
      this.unitOptions = [];
      this.floorOptions = [];
      this.queryParams.unitId = undefined;
      this.queryParams.floorId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房屋管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getHome(id).then(async response => {
        this.form = response.data;
        // 确保先加载校区和楼栋数据
        if (this.form.cellId) {
          // 转换为数字类型
          this.form.cellId = parseInt(this.form.cellId);
          await listUnit2({ cellId: this.form.cellId }).then(response => {
            this.unitOptions = response.rows;
          });
        }
        if (this.form.unitId) {
          // 转换为数字类型
          this.form.unitId = parseInt(this.form.unitId);
          await listFloor2({ unitId: this.form.unitId }).then(response => {
            this.floorOptions = response.rows;
          });
        }
        // 确保楼层ID为数字类型
        if (this.form.floorId) {
          this.form.floorId = parseInt(this.form.floorId);
        }
        // 确保其他数值类型字段正确转换
        if (this.form.roomTypeId) {
          this.form.roomTypeId = parseInt(this.form.roomTypeId);
        }
        if (this.form.roomStatus) {
          this.form.roomStatus = parseInt(this.form.roomStatus);
        }
        if (this.form.rentablePersonQuantity) {
          this.form.rentablePersonQuantity = parseInt(this.form.rentablePersonQuantity);
        }
        this.open = true;
        this.title = "修改房屋管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHome(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHome(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除房屋管理编号为"' + ids + '"的数据项？').then(function() {
        return delHome(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lock/home/export', {
        ...this.queryParams
      }, `home_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
